package spring.security.core.util;

import java.io.IOException;
import java.io.StringWriter;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import spring.security.core.support.JsonObjectMapper;

public class JsonUtils {

	private static final ObjectMapper objectMapper = new JsonObjectMapper();

	public static ObjectMapper getObjectmapper() {
		return objectMapper;
	}

	public static String toJson(Object object) {
		StringWriter writer = new StringWriter();

		try {
			objectMapper.writeValue(writer, object);
		} catch (IOException arg2) {
			arg2.printStackTrace();
		}

		return writer.toString();
	}

	public static String toJson(ObjectMapper objMap, Object object) {
		StringWriter writer = new StringWriter();

		try {
			if (objMap == null) {
				objectMapper.writeValue(writer, object);
			} else {
				objMap.writeValue(writer, object);
			}
		} catch (IOException arg3) {
			arg3.printStackTrace();
		}

		return writer.toString();
	}

	public static <T> T parse(String json, Class<T> clazz) {
		try {
			return objectMapper.readValue(json, clazz);
		} catch (IOException arg2) {
			arg2.printStackTrace();
			return null;
		}
	}

	public static <T> T parse(ObjectMapper objMap, String json, Class<T> clazz) {
		try {
			return objMap == null ? objectMapper.readValue(json, clazz) : objMap.readValue(json, clazz);
		} catch (IOException arg3) {
			arg3.printStackTrace();
			return null;
		}
	}

	public static <T> T parse(String json, TypeReference<T> type) {
		try {
			return objectMapper.readValue(json, type);
		} catch (IOException arg2) {
			arg2.printStackTrace();
			return null;
		}
	}

	public static <T, K> T parseToCollection(String json, Class<T> collectionClass, Class<K> elementClasse) {
		try {
			JavaType e = objectMapper.getTypeFactory().constructParametricType(collectionClass,
					new Class[] { elementClasse });
			return objectMapper.readValue(json, e);
		} catch (IOException arg3) {
			arg3.printStackTrace();
			return null;
		}
	}
	
}
